import configparser

from agentscope.message import Msg
from Server.managers.nodes.baseGraphNode import BaseGraphNode
from AlgoriAgent.projects.commonAgent.agents.commonAgent import CommonAgent
from .sessionInfo import SessionInfo

class AgantGraphNode(BaseGraphNode):
    def __init__(self, id:str, data:dict, graphNodeManager, random_key:str):
        super().__init__(id, data, graphNodeManager, random_key)
        self.name = data['data']['name']
        self.role = data['data']['role']
        self.prompt = data['data']['prompt']
        self.isSpeak = data['data'].get('isSpeak', True)
        self.isFunctionCall = data['data'].get('isFunctionCall', False)
        self.customKey = None
        if data['data'].get('has_custom_key', False):
            self.customKey = data['data']['custom_key'] # {'key':{'name':'name', 'type':'type', 'description':'description'}}
        self.agent = CommonAgent(name = self.name, sys_prompt = self.prompt, model_config_name = 'openai_cfg', isSpeak = self.isSpeak, isFunctionCall = self.isFunctionCall, customKey = self.customKey)

    def execute(self, session_info: SessionInfo=None):
        if session_info is None: return 
        print(self.dict)
        query = ""
        if 'query-msg' in self.dict['in']: # {'nodeId': sourceID, 'handle': sourceHandle}
            queryFrom = self.dict['in']['query-msg']
            prenode =self.graphNodeManager.nodesByIdDict[queryFrom['nodeId']]
            query = prenode.get_newest_output_in_session(session_info, queryFrom['handle'])
        
        if 'context-msg' in self.dict['in']:
            contextFrom = self.dict['in']['context-msg']
            prenode = self.graphNodeManager.nodesByIdDict[contextFrom['nodeId']]
            context = prenode.get_newest_output_in_session(session_info, contextFrom['handle'])
            self.agent.context = context

        if 'memory-msgs' in self.dict['in']:
            memoryFrom = self.dict['in']['memory-msgs']
            prenode = self.graphNodeManager.nodesByIdDict[memoryFrom['nodeId']]
            memorys = prenode.get_newest_output_in_session(session_info, memoryFrom['handle'])
            self.agent.memory = memorys

        if 'tools' in self.dict['in']:
            toolsFrom = self.dict['in']['tools']
            prenode = self.graphNodeManager.nodesByIdDict[toolsFrom['nodeId']]
            tools = prenode.get_newest_output_in_session(session_info, toolsFrom['handle'])
            self.agent.tools = tools
        try:
            returnMsg = self.agent.reply(Msg('user', query ,'user'))
            returnMsg = returnMsg['content']
        except Exception as e:
            print("在调用agent的reply函数时出错")
            print(e)
            return None

        if session_info.id not in self.dict['out']: self.dict['out'][session_info.id] = {}

        if('thought' in returnMsg):
            if 'reason-msg' not in self.dict['out'][session_info.id]: self.dict['out'][session_info.id]['reason-msg'] = []
            self.dict['out'][session_info.id]['reason-msg'].append(returnMsg['thought'])
        if('speak' in returnMsg):
            if 'speak-msg' not in self.dict['out'][session_info.id]: self.dict['out'][session_info.id]['speak-msg'] = []
            self.dict['out'][session_info.id]['speak-msg'].append(returnMsg['speak'])
        if ('functions' in returnMsg):
            if('function-calls' not in self.dict['out'][session_info.id]): self.dict['out'][session_info.id]['function-calls'] = []
            self.dict['out'][session_info.id]['function-calls'].append(returnMsg['functions'])
        self.executed_num += 1
        self.flow_next(session_info)

    
    def flow_next(self, session_info: SessionInfo):
        return super().flow_next(session_info)